package com.yowasa.xiuxian.engine.message.activity;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruiyun.jvppeteer.util.StringUtil;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.FicMsg;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.FicHelper;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.WareHoustHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@CMD(name = "/fic")
public class GouShiHandler extends CmdMessageHandler {
    public static final Logger logger = LoggerFactory.getLogger(GouShiHandler.class);
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private WareHoustHelper wareHoustHelper;
    @Autowired
    private FicHelper ficHelper;



    @Override
    public void execute(SendMessage message) {

        if(Integer.parseInt(message.getVilla_id())!=17503){
            throw new HandlerException("这是虚构史学学会的定制指令，无法在其别野外使用");
        }
        String userId = message.getFrom_user_id();

        List<String> params = getAllParam(message);//获取名称
        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可以在后面追加 保存 查看 删除 设置标题");
            return;
        }

        if ("授权".equals(params.get(0)) && (userId.equals("306512142") || userId.equals("254576762")) ) {
            String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
            if (StringUtil.isEmpty(atUserId)) {
                throw new HandlerException("需要at对方才能授权");
            }
            wareHoustHelper.insertWolfEmpower(atUserId,3);
            messageHelper.replyMys(message,"授权成功");
        }
        if ("取消授权".equals(params.get(0)) && (userId.equals("306512142") || userId.equals("254576762")) ) {
            String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
            if (StringUtil.isEmpty(atUserId)) {
                throw new HandlerException("需要at对方才能取消授权");
            }
            wareHoustHelper.deleteWolfEmpower(atUserId,3);
            messageHelper.replyMys(message,"取消授权成功");
        }
        if ("保存".equals(params.get(0))){
            params.remove(0);
            StringBuilder sb = new StringBuilder();
            params.forEach(e -> {
                sb.append(e).append("\n");
            });

            FicMsg ficMsg = new FicMsg();
            ficMsg.setTitle(message.getNickname()+ RandomUtil.randomString(5));
            ficMsg.setMsg(sb.toString());
            ficMsg.setUserId(userId);
            ficHelper.insertFic(ficMsg);
            messageHelper.replyMys(message,"保存成功，文件编号为："+ficMsg.getId());
        }
        if ("查看".equals(params.get(0))){
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("输入标题或编号进行精确查寻，如不输入内容，则查看所有当前已存在的文件。");
            if(params.size() == 1){
                List<FicMsg> list = ficHelper.list();
                stringBuffer.append("\n");
                list.forEach(e -> {
                    stringBuffer.append("\n").append(e.getId()).append(". ").append(e.getTitle());
                });
            }else {
                String s = params.get(1);
                Integer i = null;
                if(NumberUtil.isInteger(s)){
                    i = Integer.parseInt(s);
                }
                List<FicMsg> list = ficHelper.queryByIdOrTitle(s,i);
                stringBuffer.append("\n\n");
                if(list.size() == 0){
                    stringBuffer.append("未查到对应的文件，请检查输入是否有误");
                }else {
                    stringBuffer.append("文件编号：  ").append(list.get(0).getId()).append("\n文件标题：  ").append(list.get(0).getTitle()).append("\n文件内容：\n").append(list.get(0).getMsg());
                }
            }
            messageHelper.replyMys(message,stringBuffer.toString());
        }
        if ("删除".equals(params.get(0))){

            String flag = wareHoustHelper.checkAdmin(userId,3);
            if(flag == null){
                throw new HandlerException("你没有删除文件的权限，请联系管理员");
            }

            Integer fileId;
            try {
                fileId = Integer.parseInt(params.get(1));
            }catch (Exception e){
                throw new HandlerException("输入的文件编号有误，请重试");
            }

            ficHelper.deleteById(fileId);
            messageHelper.replyMys(message,"删除成功");
        }
        if ("设置标题".equals(params.get(0))){
            if(params.size() < 3){
                throw new HandlerException("指令格式有误，示例  /fic 设置标题 文件编号 标题名称");
            }
            try {
                int i = Integer.parseInt(params.get(1));
                FicMsg ficMsg = ficHelper.selectById(i);
                if(ObjectUtil.isNull(ficMsg)){
                    throw new HandlerException("不存在这样的文件，请确认文件编号是否正确");
                }
                ficMsg.setTitle(params.get(2));
                ficHelper.updateById(ficMsg);
                messageHelper.replyMys(message,"修改标题成功！");
            }catch (Exception e){
                throw new HandlerException("执行失败，请检查指令格式是否正确");
            }

        }


    }


    public String desc() {
        return "深渊挑战";
    }


}
